/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jmooc.dao.jpa;

import com.jmooc.dao.UserDao;
import com.jmooc.entity.User;
import com.jmooc.entity.User_;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 *
 * @author Group
 */
@Stateless
public class JpaUserDao implements UserDao {
    
    @PersistenceContext
    private EntityManager em;

    @Override
    public void create(User user) {
        em.persist(user);
    }

    @Override
    public void update(User user) {
        em.merge(user);
    }

    @Override
    public User getByLogin(String login) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<User> query = cb.createQuery(User.class);
        Root<User> user = query.from(User.class);
        
        List<Predicate> predicates = new ArrayList<Predicate>();
        
        predicates.add(
            cb.equal(user.get(User_.email), login)
        );
        
        query.where(predicates.toArray(new Predicate[predicates.size()]));
        
        return em.createQuery(query).getSingleResult();
        //return (User) em.createQuery("SELECT u from User u WHERE u.email = :m").setParameter("m", login).getSingleResult();
    }

    @Override
    public User getById(Long id) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<User> query = cb.createQuery(User.class);
        Root<User> user = query.from(User.class);
        
        List<Predicate> predicates = new ArrayList<Predicate>();
        
        predicates.add(
            cb.equal(user.get(User_.id), id)
        );
        
        query.where(predicates.toArray(new Predicate[predicates.size()]));
        
        return em.createQuery(query).getSingleResult();
        //return em.find(User.class, id);
        //return (User) em.createQuery("SELECT u from User u WHERE u.id = :i").setParameter("i", id).getSingleResult();
    }

    @Override
    public User getByToken(String token) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<User> query = cb.createQuery(User.class);
        Root<User> user = query.from(User.class);
        
        List<Predicate> predicates = new ArrayList<Predicate>();
        
        predicates.add(
            cb.equal(user.get(User_.token), token)
        );
        
        query.where(predicates.toArray(new Predicate[predicates.size()]));
        
        return em.createQuery(query).getSingleResult();
    }
 

}
